#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "constants.h"
#include "global.h"
#include "data_structure/linked_list.h"
#include "string/string.h"
#include "parser/parser.h"
#include "cmd/cmd.h"
#include "history/history.h"
#include "terminal/terminal.h"
#include "variable/variable.h"

void init(void);
void end(void);
void print_prompt(void);


int main(int argc, char **argv)
{
    string *input = NULL;
    string *inputaux;
    command *cmd;
    int ret;
    int stop = 0;
    int incompleteFlag = 0;

    init();

    if(system("clear") == -1) perror("Couldn't clean the mustash\n");

    while(!stop)
    {
        if(incompleteFlag)
        {
            printf("> ");
            inputaux = str_read_line();
            str_catc(input, '\n');
            str_cat(input, inputaux);
            str_delete(inputaux);
        }
        else
        {
            print_prompt();
            input = str_read_line();
        }

        cmd = command_new();
        ret = parser_parse(input, cmd);

        if(ret == INCOMPLETE) incompleteFlag = 1;
        else if(ret == EXIT) stop = 1;

        else if(!command_is_empty(cmd))
        {
            history_add(input);
            ret = execute_command(cmd);
            if(ret == EXIT) stop = 1;
            incompleteFlag = 0;
        }

        if(!incompleteFlag) str_delete(input);
        command_delete(cmd);

        if(str_lenght(msg) > 0)
        {
            str_print(msg, stdout);
        	str_delete(msg);
        	msg = str_new();
        }
	}

    end();

    return 0;
}

void init(void)
{
    string *spath = str_new();

    /* Sinais */
    set_signals_callbacks();

    /* Path */
    str_cats(spath, getenv("PATH"));
    path = ll_new();
    parser_tokenize(spath, path, ':');
    str_delete(spath);

    /* Lista dos processos */
    process_list = ll_new();

    /* Lista das variáveis */
    variable_list = ll_new();

    msg = str_new();

    /* Modo não-canônico */
    /*set_input_mode();*/
}

void end(void)
{
    ll_delete(path, str_delete); /* Path */
    ll_delete(process_list, free); /* Lista dos processos */
    ll_delete(variable_list, variable_delete); /* Lista das variáveis */
    /*reset_input_mode();*/ /* Modo canônico */
}

void print_prompt(void)
{
    printf("%s: %s $> ", getenv("USER"), getenv("PWD"));
}
